﻿using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace Game.EnemyScripts
{
    class LaserShooter:IEnemy
    {
        private readonly Level _level;
        private Vector2 _position;
        private readonly Texture2D _texture;
        private readonly Texture2D _laserTexture;
        private readonly List<Laser> _lasers = new List<Laser>();

        private float _rotation;
        private readonly int _speed;


        public LaserShooter(Level level, Vector2 position, int speed, Texture2D texture, Texture2D laserTexture)
        {
            _level = level;
            _position = position;
            _speed = speed;
            _texture = texture;
            _laserTexture = laserTexture;

            var x = new Laser(new Vector2(-10000,-10000), _laserTexture, _rotation);
            _lasers.Add(x);
            
        }
        
        public void Draw(GameTime gameTime, SpriteBatch spriteBatch)
        {
            spriteBatch.Draw(_texture, _position, null, Color.White, _rotation, new Vector2(_texture.Width / 2f, _texture.Height / 2f), 1, SpriteEffects.None, 0);
            foreach (var laser in _lasers)
            {
                laser.Draw(gameTime,spriteBatch);
            }
        }

        public void Update(GameTime gameTime)
        {
            if ((int)gameTime.TotalGameTime.TotalMilliseconds % _speed == 0)
            {
                _lasers.RemoveAt(0);
                var x = new Laser(_position, _laserTexture, _rotation);
                _lasers.Add(x);
            }
            //Calculate the distance from the square to the mouse's X and Y position
            float xDistance = _position.X - _level.Player.Position.X;
            float yDistance = _position.Y - _level.Player.Position.Y;

            //Calculate the required rotation by doing a two-variable arc-tan
            _rotation = (float)Math.Atan2(-yDistance, -xDistance);
            foreach (var laser in _lasers)
            {
                laser.Update(gameTime);
            }

        }

        public Rectangle GetBoundingRect()
        {
            if(_lasers.Capacity > 0)
                return _lasers[0].GetBoundingRect();
            else
            {
                var rect = new Rectangle((int)_position.X, (int)_position.Y, _texture.Width, _texture.Height);
                return rect;
            }
        }
    }
}
